import { ref } from 'vue'
import { useCurrActStroe } from '@/stores/currActStore'
import { storeToRefs } from 'pinia'
import { useModalStore } from '@/stores/modalStore'
import { useAsyncAxios } from '@/utils/asyncFuncStore'
import { useCardStore } from '@/stores/cardStore'
import type { CommentData, ErrorData } from '@/types/loginType'
export default function () {
  const { currUser } = storeToRefs(useCurrActStroe())
  const isShowSend = ref(false)
  function focus() {
    isShowSend.value = true
  }
  const textarea = ref<HTMLTextAreaElement | null>(null)
  // 发表评论
  async function sendComment() {
    const msg = (textarea.value as HTMLTextAreaElement).value
    const { changeData } = useModalStore()
    if (!msg) {
      // 空值
      changeData({ status: -1, data: { msg: '内容不能为空' } })
    } else {
      if (msg.trim()) {
        const { thisArt } = storeToRefs(useCardStore())
        const { sendComment } = useAsyncAxios()
        // 发送 评论数据
        const formData = {
          articleId: thisArt.value.id,
          userId: currUser.value.id,
          msg: msg
        }

        const { status, data } = await sendComment(formData)
        if (status === 200) {
          changeData({ status: status, data: { msg: '评论成功' } })
          ;(textarea.value as HTMLTextAreaElement).value = ''
        } else {
          changeData({ status: -1, data: data as ErrorData })
        }
      } else {
        // 空格
        changeData({ status: -1, data: { msg: '内容不能为空' } })
      }
    }
  }
  return {
    currUser,
    isShowSend,
    textarea,
    focus,
    sendComment
  }
}
